package com.tomato.dynamic.threadpool.core.support;

import com.tomato.dynamic.threadpool.common.queue.BlockingQueueInfo;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 队列信息
 *
 * @author lizhifu
 * @date 2022/4/8
 */
public class BlockingQueueInfoBuilder {
    /**
     * 线程池
     */
    private ThreadPoolExecutor threadPoolExecutor;

    private BlockingQueueInfoBuilder(ThreadPoolExecutor threadPoolExecutor) {
        this.threadPoolExecutor = threadPoolExecutor;
    }

    public BlockingQueueInfo build() {
        BlockingQueue<Runnable> queue = threadPoolExecutor.getQueue();
        // 队列元素个数
        int queueSize = queue.size();
        // 队列类型
        String queueType = queue.getClass().getSimpleName();
        // 队列剩余容量
        int remainingCapacity = queue.remainingCapacity();
        // 队列容量
        int queueCapacity = queueSize + remainingCapacity;


        BlockingQueueInfo blockingQueueInfo = new BlockingQueueInfo();
        blockingQueueInfo.setQueueName(queueType);
        blockingQueueInfo.setQueueCapacity(queueCapacity);
        blockingQueueInfo.setQueueSize(queueSize);
        blockingQueueInfo.setRemainingCapacity(remainingCapacity);

        return blockingQueueInfo;
    }
    private BlockingQueueInfoBuilder() {}

    public static BlockingQueueInfoBuilder newBuilder(ThreadPoolExecutor threadPoolExecutor) {
        return new BlockingQueueInfoBuilder(threadPoolExecutor);
    }
}
